package com.bmadmin.controller.sms;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.bmadmin.domain.AddressUser;
import com.bmadmin.domain.LayUiDataTablePOJO;
import com.bmadmin.domain.MessageDomain;
import com.bmadmin.domain.NormalResult;
import com.bmadmin.domain.NoticeDomain;
import com.bmadmin.domain.SysDepartmentsPOJO;
import com.bmadmin.domain.SysUsersPOJO;
import com.bmadmin.service.AddressService;
import com.bmadmin.util.BMUtil;
import com.bmadmin.util.Constants;
import com.bmadmin.util.Util;
import com.github.stuxuhai.jpinyin.PinyinException;

@RestController
@RequestMapping("/address")
public class addressController {
	private Logger logger = LogManager.getLogger(this.getClass().getName());
    @Autowired
    AddressService addressService;
    /**
     * 获取通讯录分类列表树
     */
    @GetMapping("/getTreeList")
    public NormalResult getAddressTreeList(SysDepartmentsPOJO sysDepartmentsPOJO){
        NormalResult result = addressService.getAddressTreeList(sysDepartmentsPOJO);
        logger.info(result);
        return result;
    }
    
    /**
     * 获取分类信息
     */
    @GetMapping("/getById")
    public NormalResult getDepartmentById(SysDepartmentsPOJO sysDepartmentsPOJO){
        NormalResult result = new NormalResult();
        if(BMUtil.isNullOrEmpty(sysDepartmentsPOJO)){
            result.setCode("9999");
            result.setMsg("传入数据为空");
            return result;
        }
        if("".equals(BMUtil.NulltoString(sysDepartmentsPOJO.getD_id()))){
            result.setCode("9999");
            result.setMsg("传入分类id为空");
            return result;
        }
        result=addressService.getDepartmentById(sysDepartmentsPOJO);
        return result;

    }
    
    /**
     * 新增部门
     */
    @PostMapping("/insertDepartment")
    public NormalResult insertDepartment(SysDepartmentsPOJO sysDepartmentsPOJO){
        NormalResult result = new NormalResult();
        if(BMUtil.isNullOrEmpty(sysDepartmentsPOJO)){
            result.setCode("9999");
            result.setMsg("传入数据为空");
            return result;
        }
        if("".equals(BMUtil.NulltoString(sysDepartmentsPOJO.getD_name()))){
            result.setCode("9999");
            result.setMsg("传入分类名称为空");
            return result;
        }
        if("".equals(BMUtil.NulltoString(sysDepartmentsPOJO.getD_part_id()))){
            result.setCode("9999");
            result.setMsg("传入父级分类id为空");
            return result;
        }
        int d_id = 0;
        if("00".equals(sysDepartmentsPOJO.getD_part_id())){
            d_id = addressService.getNextDepartId(sysDepartmentsPOJO.getD_part_id());
        }else{
            d_id = addressService.getNextDId(sysDepartmentsPOJO.getD_part_id());
            if(d_id==1){
            	d_id = Integer.parseInt(sysDepartmentsPOJO.getD_part_id()+"01");
            }
        }
        sysDepartmentsPOJO.setD_id(String.valueOf(d_id));
        result = addressService.insertDepartment(sysDepartmentsPOJO);

        return result;
    }
    
    /**
     * 修改部门
     */
    @PostMapping("/updateDepartment")
    public NormalResult updateDepartment(SysDepartmentsPOJO sysDepartmentsPOJO){
        NormalResult result = new NormalResult();
        if(BMUtil.isNullOrEmpty(sysDepartmentsPOJO)){
            result.setCode("9999");
            result.setMsg("传入数据为空");
            return result;
        }
        if("".equals(BMUtil.NulltoString(sysDepartmentsPOJO.getD_id()))){
            result.setCode("9999");
            result.setMsg("传入分类id为空");
            return result;
        }
        if("".equals(BMUtil.NulltoString(sysDepartmentsPOJO.getD_name()))){
            result.setCode("9999");
            result.setMsg("传入分类名称为空");
            return result;
        }

        result = addressService.updateDepartment(sysDepartmentsPOJO);

        return result;
    }
    
    /**
     * 删除部门
     */
    @PostMapping("/deleteDepartment")
    public NormalResult deleteDepartment(SysDepartmentsPOJO sysDepartmentsPOJO){
        NormalResult result = new NormalResult();
        if(BMUtil.isNullOrEmpty(sysDepartmentsPOJO)){
            result.setCode("9999");
            result.setMsg("传入数据为空");
            return result;
        }
        if("".equals(BMUtil.NulltoString(sysDepartmentsPOJO.getD_id()))){
            result.setCode("9999");
            result.setMsg("传入分类id为空");
            return result;
        }

        result = addressService.delDepartment(sysDepartmentsPOJO);
        return result;

    }
    
    /**
     * 获取用户列表
     */
    @GetMapping("/getUsers")
    public LayUiDataTablePOJO getUserList(AddressUser addressUser) {
        LayUiDataTablePOJO result = addressService.getUserList(addressUser);
        logger.info(result);
        return result;
    }
    
    /**
     * 用户新增
     */
    @PostMapping("/insertUser")
    public NormalResult insertUser(AddressUser addressUser) {
        NormalResult result = new NormalResult();
        if (BMUtil.isNullOrEmpty(addressUser)) {
            result.setCode("9999");
            result.setMsg("传入数据为空");
            return result;
        }

        if (BMUtil.isNullOrEmpty(addressUser.getU_name())) {
            result.setCode("9999");
            result.setMsg("人员名称不能为空");
            return result;
        }
        if (BMUtil.isNullOrEmpty(addressUser.getD_id())) {
            result.setCode("9999");
            result.setMsg("分类ID传输错误");
            return result;
        }
        if (BMUtil.isNullOrEmpty(addressUser.getU_phone())) {
            result.setCode("9999");
            result.setMsg("手机号码不可为空");
            return result;
        }
        try {
            result = addressService.insertUser(addressUser);
        } catch (Exception e) {
            result.setCode("9999");
            result.setMsg("人员新增出现异常");
            logger.error(e);
        }
        return result;
    }
    
    /**
     * 用户修改
     */
    @PostMapping("/updateUser")
    public NormalResult updateUser(AddressUser addressUser){
        NormalResult result = new NormalResult();
        if (BMUtil.isNullOrEmpty(addressUser)) {
            result.setCode("9999");
            result.setMsg("传入数据为空");
            return result;
        }
        if (BMUtil.isNullOrEmpty(addressUser.getU_name())) {
            result.setCode("9999");
            result.setMsg("人员名称不能为空");
            return result;
        }
        if (BMUtil.isNullOrEmpty(addressUser.getU_id())) {
            result.setCode("9999");
            result.setMsg("人员ID传输错误");
            return result;
        }
        if (BMUtil.isNullOrEmpty(addressUser.getU_phone())) {
            result.setCode("9999");
            result.setMsg("手机号码不可为空");
            return result;
        }
        result = addressService.updateUser(addressUser);
        return result;
    }
    
    /**
     * 用户删除
     */
    @PostMapping("/deleteUser")
    public NormalResult deleteUser(AddressUser addressUser) {
        NormalResult result = new NormalResult();
        if(BMUtil.isNullOrEmpty(addressUser.getU_id())){
            result.setCode("9999");
            result.setMsg("人员ID为空!");
            return result;
        }
        result = addressService.deleteUser(addressUser.getU_id());
        return result;
    }
    
    /**
     * 批量人员删除
     */
    @PostMapping("/deletePlUser")
    public NormalResult deletePlUser(HttpSession session, String JsonStr) {
        SysUsersPOJO user = (SysUsersPOJO) session.getAttribute(Constants.USER_INFO_SESSION);
        NormalResult result = new NormalResult();
        try {
            List<Map> list = Util.jsonToList(JsonStr);
            if (list == null || list.size() == 0) {
            	result.setCode("9999");
                result.setMsg("未勾选需要删除的记录！");
            } else {
                for (Map info : list) {
                    //删除预发送列表对应的数据
                	addressService.deleteUser(BMUtil.Object2String(info.get("u_id")));
                }
                result.setCode("0000");
                result.setMsg("批量删除成功！");
            }
        } catch (Exception e) {
            result.setCode("9999");
            result.setMsg("批量删除异常！");
            logger.error(e);
        }
        return result;
    }
    
    /**
     * 模板下载
     *
     * @param request
     * @param response
     */

    @RequestMapping(value = "/downloadfile")
    public void downloadfile(HttpServletRequest request,
                             HttpServletResponse response) throws IOException {

        //初始一个workbook

        HSSFWorkbook workbook = new HSSFWorkbook();


        // 设置单元格类型
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平布局：居中
        cellStyle.setWrapText(true);

        HSSFSheet sheet = workbook.createSheet();
        // 在sheet中添加表头第0行
        // 用于格式化单元格的数据
        HSSFDataFormat format = workbook.createDataFormat();
        HSSFCellStyle stylecol = workbook.createCellStyle();
        stylecol.setDataFormat(format.getFormat("@"));

        CellRangeAddress aa = new CellRangeAddress(0, 0, 0, 6);
        HSSFRow rowthead = sheet.createRow((int) 0);


        sheet.addMergedRegion(aa);
        HSSFRow row = sheet.createRow((int) 1);
        sheet.autoSizeColumn(1, true);

        HSSFFont font = workbook.createFont();
        HSSFFont fontthead = workbook.createFont();
        // font.setFontName("黑体");
        fontthead.setFontHeightInPoints((short) 16);//设置字体大小
//				font.setFontName("仿宋_GB2312");
        fontthead.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 粗体显示
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 粗体显示
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 粗体显示

        // 创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = workbook.createCellStyle();
        HSSFCellStyle stylethead = workbook.createCellStyle();
        stylethead.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
        stylethead.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
        stylethead.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
        stylethead.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
        stylethead.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框

        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
        stylethead.setFont(fontthead);

        HSSFCell cellthead = rowthead.createCell(0);
        cellthead.setCellValue("通讯录导入模板");
        cellthead.setCellStyle(stylethead);

        HSSFCell cell = row.createCell(0);

        cell = row.createCell(0);
        cell.setCellValue("姓名（必填）");
        cell.setCellStyle(style);
        sheet.setDefaultColumnStyle(0, stylecol);
        sheet.setColumnWidth(0, (int) (35.7 * 100));

        cell = row.createCell(1);
        cell.setCellValue("手机号（必填）");
        cell.setCellStyle(style);
        sheet.setDefaultColumnStyle(1, stylecol);
        sheet.setColumnWidth(1, (int) (35.7 * 100));

        cell = row.createCell(2);
        cell.setCellValue("企业税号");
        cell.setCellStyle(style);
        sheet.setDefaultColumnStyle(2, stylecol);
        sheet.setColumnWidth(2, (int) (35.7 * 100));

        cell = row.createCell(3);
        cell.setCellValue("企业名称");
        cell.setCellStyle(style);
        sheet.setDefaultColumnStyle(3, stylecol);
        sheet.setColumnWidth(3, (int) (35.7 * 100));
        
        cell = row.createCell(4);
        cell.setCellValue("固定电话");
        cell.setCellStyle(style);
        sheet.setDefaultColumnStyle(4, stylecol);
        sheet.setColumnWidth(4, (int) (35.7 * 100));
        
        cell = row.createCell(5);
        cell.setCellValue("邮箱地址");
        cell.setCellStyle(style);
        sheet.setDefaultColumnStyle(5, stylecol);
        sheet.setColumnWidth(5, (int) (35.7 * 100));
        
        cell = row.createCell(6);
        cell.setCellValue("联系地址");
        cell.setCellStyle(style);
        sheet.setDefaultColumnStyle(6, stylecol);
        sheet.setColumnWidth(6, (int) (35.7 * 100));


        workbook.write(response.getOutputStream());
        String filename = "通讯录导入模板.xls";
        filename = java.net.URLEncoder.encode(filename, "UTF-8");
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename="
                + filename);
        response.addHeader("Content-Length", "");
        OutputStream toClient = new BufferedOutputStream(
                response.getOutputStream());
        response.setContentType("application/octet-stream");


    }
    
    @PostMapping(value = "uploadfile")
    public NormalResult uploadfile(HttpSession session,MultipartFile file,String d_id)throws IOException {
        SysUsersPOJO user = (SysUsersPOJO) session.getAttribute(Constants.USER_INFO_SESSION);
        NormalResult result = new NormalResult();
        InputStream is = null;
        try {
            // 判断文件是否为空
            if (file == null) {
                result.setCode("9999");
                result.setMsg("文件不能为空！");
                return result;
            }

            // 获取文件名
            String fileName = file.getOriginalFilename();

            if (!BMUtil.validateExcel(fileName)) {
                result.setCode("9999");
                result.setMsg("文件必须是excel文件！");
                return result;
            }
            
            if(BMUtil.Object2String(d_id).equals("")){
            	result.setCode("9999");
                result.setMsg("请先选中左侧分类树");
                return result;
            }
            
            is = file.getInputStream();
//			Workbook wb = new XSSFWorkbook(is);
            Workbook wb = WorkbookFactory.create(is);
            // 得到第一个shell
            Sheet sheet = wb.getSheetAt(0);
            // 得到Excel的行数
            int totalRows = sheet.getLastRowNum() + 1 - sheet.getFirstRowNum();
            // 错误信息接收器
            String errorMsg = "";
            String br = "<br/>";
            for (int i = 2; i < totalRows; i++) {
            	AddressUser addressUser = new AddressUser();
                Row row = sheet.getRow(i);
                String u_name = BMUtil.Object2String(row.getCell(0));
                if (u_name.equals("")) {
                    errorMsg += br + "第" + (i + 1) + "行人员姓名为空";
                    continue;
                }
                String u_phone = BMUtil.Object2String(row.getCell(1));
                if (u_phone.equals("")) {
                    errorMsg += br + "第" + (i + 1) + "行手机号码为空";
                    continue;
                }
                if(!BMUtil.checkMobileNumber(u_phone)){
                	errorMsg += br + "第" + (i + 1) + "行手机号码错误";
                    continue;
                }
                String u_nsrsbh = BMUtil.Object2String(row.getCell(2));
                String u_nsrmc = BMUtil.Object2String(row.getCell(3));
                String u_gddh = BMUtil.Object2String(row.getCell(4));
                String u_email = BMUtil.Object2String(row.getCell(5));
                String u_address = BMUtil.Object2String(row.getCell(6));

                addressUser.setU_name(u_name);
                addressUser.setU_phone(u_phone);
                addressUser.setU_nsrsbh(u_nsrsbh);
                addressUser.setU_nsrmc(u_nsrmc);
                addressUser.setU_gddh(u_gddh);
                addressUser.setU_email(u_email);
                addressUser.setU_address(u_address);
                addressUser.setD_id(d_id);
                addressService.insertUser(addressUser);
            }
            String msg = "文件上传成功！";
            if (!errorMsg.equals("")) {
                msg = errorMsg;
            }
            result.setCode("0000");
            result.setMsg(msg);
            return result;
        } catch (Exception e) {
            result.setCode("9999");
            result.setMsg("文件上传异常！");
            logger.error(e);
            return result;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    is = null;
                    e.printStackTrace();
                }
            }
        }
    }
}
